import SliderCaptcha from 'rc-slider-captcha';
import React, { useRef } from 'react';
import { createPuzzle } from 'create-puzzle';
import DemoImage from '../assets/bg2.jpg';
import { useUpdateEffect } from 'rc-hooks';
import { useNavigate } from 'react-router-dom';
import http from '../utils/request';
import { message } from "antd";

export default function Captcha({ phonenumber, password }) {
    const [messageApi, contextHolder] = message.useMessage();
    const sliderCaptchaRef = useRef(); // 滑块验证码引用
    const expectedOffsetX = useRef(0); // 预期X轴偏移量
    const navigate = useNavigate(); // 路由导航函数

    useUpdateEffect(() => {
        sliderCaptchaRef.current?.refresh(); // 刷新滑块验证码
    }, []);

    const handleVerify = async (data) => {
        const tolerance = 5; // 容差值
        if (data.x >= expectedOffsetX.current - tolerance && data.x < expectedOffsetX.current + tolerance) {
            try {
                const response = await http.post('/pc_login', { phonenumber, password });
                const { code, accessToken, refreshToken, msg, adminId } = response.data;

                if (code === 200) {
                    messageApi.open({
                        type: 'success',
                        content: msg,
                    });
                    localStorage.setItem('accessToken', accessToken); // 存储访问令牌
                    localStorage.setItem('refreshToken', refreshToken); // 存储刷新令牌
                    sessionStorage.setItem('adminId', adminId); // 存储管理员ID
                    navigate('/'); // 导航到主页
                } else {
                    sliderCaptchaRef.current?.refresh(); // 刷新滑块验证码
                    throw new Error(msg); // 抛出错误信息
                }
            } catch (error) {
                messageApi.open({
                    type: 'error',
                    content: error.message || '登录过程中发生错误。',
                });
            }
        } else {
            messageApi.open({
                type: 'error',
                content: '验证码验证失败，请重试。',
            });
            return Promise.reject();
        }
    };

    return (
        <div>
            {contextHolder}
            <SliderCaptcha
                request={() => createPuzzle(DemoImage).then(({ x, bgUrl, puzzleUrl }) => {
                    expectedOffsetX.current = x; // 设置预期X轴偏移量
                    return { bgUrl, puzzleUrl };
                })}
                onVerify={handleVerify}
                bgSize={{ width: 350 }}
                actionRef={sliderCaptchaRef}
            />
        </div>
    );
}
